import java.util.PriorityQueue;

import static java.lang.Thread.sleep;

/**
 * Creat with IntelliJ IDEA
 * Description
 * User: mamba24
 * Date: 2022-08-05
 * Time: 8:06
 * To BE A Better Person-2020-3-2
 */
//1.队列为空要阻塞，队列不为空则唤醒
//2.队列为满要阻塞，队列不为满则唤醒
class MyBlockqueue{
    //存放数据
    volatile public int[] elem=new int[10000];
    //循环队列队头
    public int head;
    //循环队列队尾
    public int end;
    //数组大小
    volatile public int size;

    public MyBlockqueue(){
        this.head=0;
        this.end=0;
        this.size=0;
    }
    //插入元素
    public void put(int val) throws InterruptedException {
        synchronized (this){
            while(size==elem.length){
                //放满了
                this.wait();
            }
            elem[end]=val;
            end++;
            //循环队列判断end是否到达队尾
            if(end== elem.length-1){
                end=0;
            }

            size++;
            this.notify();
        }

    }

    //弹出元素
    public Integer take() throws InterruptedException {
        synchronized (this){
            while(size==0){
                //没有元素
                this.wait();
            }
            int ret=elem[head];
            head++;
            if (head== elem.length-1){
                head=0;
            }
            size--;
            this.notify();
            return ret;
        }
    }

}
public class TestDemo {
    public static void main(String[] args) throws InterruptedException {
        MyBlockqueue queue=new MyBlockqueue();
        Thread customer=new Thread(()->{
            while (true){
                try {
                    int num=queue.take();
                    System.out.println("取出元素:"+num);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
        customer.start();
        Thread producer = new Thread(()->{
            int a = 0;
           while(true){
               try {
                   queue.put(a);
                   System.out.println("放入元素："+a);
                   a++;
                   sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        producer.start();
        customer.join();
        producer.join();
    }

}
